package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    //上传视频图片
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //判断视频和图片是否全部上传了
        if (videoThumbnail.isEmpty() || videoFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        //将视频上传到FastDFS,获取访问url,首先获取文件名
        String filename = videoFile.getOriginalFilename();
        //获取文件名后缀
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = fdfsWebServer.getWebServerUrl();
        //将封面上传到阿里云OSS,获取访问URL
        String imgUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //构建video对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setVideoUrl(videoUrl);
        video.setPicUrl(imgUrl);
        video.setText("牛逼");
        //调用api,保存数据
        String videoId = videoApi.save(video);
        if (videoId == null) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    //推荐视频列表
    public PageResult queryVideoList(int page, int pagesize) {
        //查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //判断redis数据是否存在,判断redis中数据是否满足分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //如果redis数据存在,根据vid查询
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总条数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map((e -> Long.valueOf(e)))
                        .collect(Collectors.toList());
                //调用api,根据pid数组查询动态数据
                list = videoApi.findMovementsByPids(vids);
            }
            PageUtil.totalPage(values.length, pagesize);
        }
        //如果redis数据不存在,分页查询视频数据
        if (list.isEmpty()) {
            list = videoApi.queryVideoList(page - redisPages, pagesize);
        }
        //提取视频数据列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //使用用户id列表,调用api查询所有用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //循环遍历list,转化为vo对象
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            if (video.getUserId() == UserHolder.getUserId()) {
                continue;
            }
            UserInfo userInfo = map.get(video.getUserId());
            VideoVo vo = VideoVo.init(userInfo, video);
            String key = Constants.VIDEOS_RECOMMEND + video.getId();
            String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
            String value = (String) redisTemplate.opsForHash().get(key, hashKey);
            if (value != null) {
                vo.setHasLiked(1);
            }
            //查询redis数据
            String key1 = Constants.VIDEOS_LOVE + video.getUserId();
            String hashKey1 = Constants.VIDEO_LOVE_HASHKEY + UserHolder.getUserId();
            String redisValue1 = (String) redisTemplate.opsForHash().get(key1, hashKey1);
            //判断redisValue是否存在
            if (redisValue1 != null) {
                vo.setHasFocus(1);
            }
            vos.add(vo);
        }

        return new PageResult(page, pagesize, 0l, vos);
    }

    //视频点赞
    public Integer videoLike(ObjectId id) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查询redis数据
        String key = Constants.VIDEOS_RECOMMEND + id;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        String redisValue = (String) redisTemplate.opsForHash().get(key, hashKey);
        //判断redisValue是否存在
        if (redisValue != null) {
            //存在抛出异常
            throw new BusinessException(ErrorResult.likeError());
        }
        redisTemplate.opsForHash().put(key, hashKey, "1");
        Integer count = videoApi.videoLike(id, CommentType.LIKE);
        return count;
    }

    //视频取消点赞
    public Integer videoDisLike(ObjectId id) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查询redis数据
        String key = Constants.VIDEOS_RECOMMEND + id;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + userId;
        String redisValue = (String) redisTemplate.opsForHash().get(key, hashKey);
        //判断redisValue是否存在
        if (redisValue == null) {
            //不存在抛出异常
            throw new BusinessException(ErrorResult.likeError());
        }
        redisTemplate.opsForHash().delete(key, hashKey);
        Integer count = videoApi.videoDisLike(id, CommentType.LIKE);
        return count;
    }

    //用户关注
    public void videoUserFocus(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查询redis数据
        String key = Constants.VIDEOS_LOVE + uid;
        String hashKey = Constants.VIDEO_LOVE_HASHKEY + UserHolder.getUserId();
        String redisValue = (String) redisTemplate.opsForHash().get(key, hashKey);
        //判断redisValue是否存在
        if (redisValue != null) {
            //存在抛出异常
            throw new BusinessException(ErrorResult.loveError());
        }
        //不存在,保存到redis
        redisTemplate.opsForHash().put(key, hashKey, "1");
        //调用api,修改MongoDB
        videoApi.videoLove(uid, CommentType.LOVE);
    }

    //用户取消关注
    public void videoUserUnFocus(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查询redis数据
        String key = Constants.VIDEOS_LOVE + uid;
        String hashKey = Constants.VIDEO_LOVE_HASHKEY + UserHolder.getUserId();
        String redisValue = (String) redisTemplate.opsForHash().get(key, hashKey);
        //判断redisValue是否存在
        if (redisValue == null) {
            //不存在抛出异常
            throw new BusinessException(ErrorResult.loveError());
        }
        //有数据,删除
        redisTemplate.opsForHash().delete(key, hashKey);
        videoApi.videoDisLove(uid, CommentType.LOVE);
    }
}
